
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_frame/app/components/loading/loading_widget.dart';

abstract class AppLoadingDialog{
  static CancelFunc? _cancelFunc;
  static int _lastTime = 0;

  /// 弹框动画时长
  static const int _animationDurationMilliseconds = 300;

  /// 显示加载弹框
  static void show({
    bool clickClose = false,
    VoidCallback? onClose,
  }) {
    _close();

    _lastTime = DateTime.now().millisecondsSinceEpoch;

    BotToast.showCustomLoading(
      clickClose: clickClose,
      onClose: onClose,
      backgroundColor: Colors.black38,
      backButtonBehavior:
      clickClose ? BackButtonBehavior.close : BackButtonBehavior.ignore,
      // wrapToastAnimation: (controller, cancel, child) =>
      //     DialogOpacityAnimation(controller: controller, child: child),
      // wrapAnimation: (controller, cancel, child) =>
      //     DialogOpacityAnimation(controller: controller, child: child),
      toastBuilder: (CancelFunc cancelFunc) {
        _cancelFunc = cancelFunc;
        return const LoadingWidget(fullPage: false);
      },
      animationDuration: const Duration(milliseconds: _animationDurationMilliseconds),
    );
  }

  static bool _close() {
    if (_cancelFunc != null) {
      _cancelFunc?.call();
      _cancelFunc = null;
      /// 动画时间内, 可能取消不成功, 强制执行取消全部
      if(DateTime.now().millisecondsSinceEpoch - _lastTime < _animationDurationMilliseconds){
        BotToast.closeAllLoading();
      }
      _lastTime = 0;
      return true;
    }
    return false;
  }

  /// 关闭加载弹框
  static void close() {
    if (!_close()) {
      closeAll();
    }
  }

  /// 取消全部, 会没有动画效果
  static void closeAll() {
    BotToast.closeAllLoading();
    _cancelFunc = null;
    _lastTime = 0;
  }
}
